using System.Globalization;
using System.Data.Common;
using System.Collections.Generic;
using AnalyStock.DataManage;

namespace AnalyStock.GrapImage;

/// <summary>
///     初始化鼠标菜单，添加或删除自选股
/// </summary>
public partial class ChartKline : UserControl
{
    /// <summary>
    /// 自选股菜单处理，自选股概念记录面板
    /// </summary>
    private void InitializeMenu_SeleStockNote()
    {
        AddSeleStockNotePanel.InitializeMouseDarg(this);
        AddSeleStockNotePanel.Visibility = Visibility.Hidden;
        BtnAddStockNote.Click += (s, e) =>
       {
           UpdateSeleStock(new MenuItem { Name = "Note" }, e);
           AddSeleStockNotePanel.Visibility = Visibility.Hidden;
       };
        BtnCancelStockNote.Click += (s, e) =>
        {
            TextBoxStockNote.Text = string.Empty;
            AddSeleStockNotePanel.Visibility = Visibility.Hidden;
        };
        //股票集合数据加载完毕后，填充菜单项-概念集合
        SeleStocksFilled += CreateSeleStockMenu;
    }
    private void CreateSeleStockMenu(object sender,
            (IList<SelectStock>, IList<Conception> Conceptions) seleStocks)
    {
        ContextMenu _contextMenu = new()
        {
            Style = SetElementStyle("ContextMenuStyle")
        };

        MenuItem menuItem_Add = new()
        {
            Header = "🔸添加自选股",
            ToolTip = "▷",
            Name = "Add",
            Style = SetElementStyle("MenuItemStyle")
        };
        seleStocks.Conceptions?.ForEach(item =>
        {
            MenuItem menuItem_Conception = new()
            {
                Header = item.Name,
                ToolTip = item.OrderID,
                Name = "Add",
                Style = SetElementStyle("MenuItemStyle")
            };
            menuItem_Conception.Click += UpdateSeleStock;
            menuItem_Add.Items.Add(menuItem_Conception);
        });
        //子菜单：删除自选股
        MenuItem menuItem_Del = new()
        {
            Header = "🔸删除自选",
            Name = "Dele",
            Style = SetElementStyle("MenuItemStyle")
        };
        menuItem_Del.Click += UpdateSeleStock;
        //子菜单：添加概念分类
        MenuItem menuItem_Classify = new()
        {
            Header = "🔸概念分类",
            Name = "Classify",
            Style = SetElementStyle("MenuItemStyle")
        };
        menuItem_Classify.Click += (s, e) =>
        {
            ConceptionClassifyPanel.Visibility = Visibility.Visible;
        };
        //子菜单：添加自选股的产品、概念题材说明
        MenuItem menuItem_StockNote = new()
        {
            Header = "🔸股票说明",
            Name = "Note",
            Style = SetElementStyle("MenuItemStyle")
        };
        menuItem_StockNote.Click += (s, e) =>
        {
            TextBoxStockNote.Text = currStockInfo.Note;
            AddSeleStockNotePanel.Visibility = Visibility.Visible;
        };
        _contextMenu.Items.Add(menuItem_Add);
        _contextMenu.Items.Add(menuItem_Del);
        _contextMenu.Items.Add(menuItem_Classify);
        _contextMenu.Items.Add(menuItem_StockNote);
        ContextMenu = _contextMenu;
    }

    //自选股或分类概念更新后，触发以实现其他窗口相关数据的更新
    internal event EventHandler<SelectStock> SeleStockChanged;
    protected void OnSeleStockChanged(SelectStock sele) =>
        SeleStockChanged?.Invoke(null, sele);

    private async void UpdateSeleStock(object sender, RoutedEventArgs e)
    {
        var currMenuItem = sender as MenuItem;
        if (currStockInfo is null) return;
        var modifySeleStock = GetFilterSeleStock();
        switch (currMenuItem)
        {
            case { Name: "Add" }://修改概念分类 
                SelectStocks.Add(modifySeleStock);
                await CommDataMethod<SelectStock>
                        .UpdateSeleStockAsync(new List<SelectStock> { modifySeleStock });
                currStockInfo.Conception = modifySeleStock.Conception;
                currStockInfo.Note = modifySeleStock.Note;
                currStockInfo.IsSele = true;
                break;
            case { Name: "Dele" }://删除自选股
                if (modifySeleStock is null)
                {
                    "不在自选股记录中，无需删除...".ErrorMessage();
                    return;
                }
                if (!"是否确认删除该自选股?".IsConfirmMessage())
                {
                    return;
                }
                SelectStocks.Remove(modifySeleStock);
                await CommDataMethod<SelectStock>
                       .DelSeleStockAsync(new List<SelectStock> { modifySeleStock });
                currStockInfo.Conception = string.Empty;
                currStockInfo.Note = string.Empty;
                currStockInfo.IsSele = false;
                break;
            case { Name: "Note" }: //修改股票备注
                if (modifySeleStock is null)
                {
                    "请保存为自选股，再注释说明...".ErrorMessage();
                    return;
                }
                if (!"是否确认保存注释?".IsConfirmMessage())
                {
                    return;
                }
                //修订备注
                modifySeleStock.Note = TextBoxStockNote.Text.Trim();
                await CommDataMethod<SelectStock>
                        .UpdateSeleStockAsync(new List<SelectStock> { modifySeleStock });
                currStockInfo.Note = modifySeleStock.Note;
                break;
        }

        //改变面板股票名称、代码提示
        TextHeaderItem();
        //传递股票改变状态，传播事件
        OnSeleStockChanged(modifySeleStock);
        //获取自选股在库数据
        SelectStock GetFilterSeleStock()
        {
            return currMenuItem.Name.Equals("Add")
                ? new SelectStock
                {
                    Id = 0,
                    Ts_code = currStockInfo.Ts_code,
                    Name = currStockInfo.Name,
                    Industry = currStockInfo.Industry,
                    Conception = (string)currMenuItem.Header,
                    OrderID = $"{(string)currMenuItem.ToolTip}.{GetMaxOrderId()}",
                    Note = currStockInfo.Note
                }
                : SelectStocks?.FirstOrDefault(
                                n => n.Ts_code.Equals(currStockInfo.Ts_code)
                                    && n.Conception.Equals(currStockInfo.Conception));
        }

        string GetMaxOrderId()
        {
            var maxStringId = SelectStocks?
                            .Where(n => n.Conception.Equals((string)currMenuItem.Header))
                            .Max(n => n.OrderID);
            if (string.IsNullOrEmpty(maxStringId)) return "00";
            var maxId = int.Parse(maxStringId.Split(".").Last());
            return maxId + 1 < 10 ? $"0{maxId + 1}" : $"{maxId + 1}";
        }


    }
}